﻿using System;
using System.Collections.Generic;
using offline2048;
using MotionFramework.Event;
using UnityEngine;

namespace GTA
{
    public class ADSPlayData
    {
        public int adType = 0; //1:rv  2:i  3:b
        public string Adid;
        public string Format;
        public string Network;
        public string InterstitialGameState;
        public DateTime DateTime;
    }

    public class ADSHelper : Singleton<ADSHelper>
    {
        public static readonly string ACTION_TYPE = "ads";
        private static long _lastShowInterstitialTime = 0;
        private static long _lastShowInterstitialLevel = 0;
        public static string InterstitialGameState = "";
        private static string _rewardVideoFrom = "";
        private static bool _rewardVideCompleted = false;
        public static bool HasPlayRV = false; //
        public static bool EditorADState = true;

        public static bool IsTryPlayAD { get; set; }

        public void Init()
        {
            EventManager.Instance.AddListener<ADEvent.GetNoAd>(HandleEvent);
        }

        /// <summary>
        /// 检测玩家最近游戏里是否在广告页面关闭了游戏
        /// </summary>
        public static void CheckAdViewBack()
        {
            //GTALogger.Log("### IsShowInterstitialCloseBack : " + AdsDataMgr.Instance.IsShowInterstitialCloseBack);
            //GTALogger.Log("### IsShowRewardVideoCloseBack : " + AdsDataMgr.Instance.IsShowRewardVideoCloseBack);
            var o = DataSaveHelper.Instance.Get(ADSHelper.ACTION_TYPE);
            if (string.IsNullOrEmpty(o))
            {
                return;
            }

            ADSPlayData data = Newtonsoft.Json.JsonConvert.DeserializeObject<ADSPlayData>(o);
            DataSaveHelper.Instance.CleanKey(ADSHelper.ACTION_TYPE);
            if (data.adType == 2)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("name", "ad_viewback_i");
                dict.Add("from", data.InterstitialGameState);
                dict.Add("network", data.Network);
                long watchTime = Utils.GetTimeStamp() - AdsDataMgr.Instance.AdInterstitialPlayTime;
                dict.Add("watchTime", watchTime / 1000);
                SendAction(dict);

                // ActionEvent.AdInterstitialDebug interstitialDebug = new ActionEvent.AdInterstitialDebug();
                // interstitialDebug.FireScene = AdsDataMgr.Instance.AdInterstitialFireScene;
                // interstitialDebug.IntervalTime =
                //     (int)((Utils.GetTimeStamp() - AdsDataMgr.Instance.AdInterstitialLastShowTime) / 1000);
                // interstitialDebug.NetWork =
                //     $"{AdsDataMgr.Instance.AdInterstitialNetwork} | {AdsDataMgr.Instance.AdInterstitialNetwork} | {AdsDataMgr.Instance.AdInterstitialNetwork}";
                // interstitialDebug.PlayAdID = AdsDataMgr.Instance.AdInterstitialID;
                // EventManager.Instance.SendMessage(interstitialDebug);
                //重置插屏广告中间信息
                AdsDataMgr.Instance.AdInterstitialNetwork = "";
                AdsDataMgr.Instance.AdInterstitialLastShowTime = 0;
                AdsDataMgr.Instance.AdInterstitialFireScene = "";
                AdsDataMgr.Instance.AdInterstitialID = "";

                AdsDataMgr.Instance.AdInterstitialViewBackCount++;
                AdsDataMgr.Instance.AdInterstitialViewBackTodayCount++;

                AdsDataMgr.Instance.IsShowInterstitialCloseBack = false;
                AdsDataMgr.Instance.SaveData();
            }

            if (data.adType == 1)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("name", "ad_viewback_rv");
                dict.Add("from", data.InterstitialGameState);
                dict.Add("network", data.Network);
                dict.Add("finish", 0);
                long watchTime = Utils.GetTimeStamp() - AdsDataMgr.Instance.AdRewardVideoPlayTime;
                dict.Add("watchTime", watchTime / 1000);
                SendAction(dict);

                // ActionEvent.AdRewardVideoDebug rvdebug = new ActionEvent.AdRewardVideoDebug();
                // rvdebug.FireScene = AdsDataMgr.Instance.AdRewardVideoFireScene;
                // rvdebug.IntervalTime =
                //     (int)((Utils.GetTimeStamp() - AdsDataMgr.Instance.AdRewardVideoLastShowTime) / 1000);
                // rvdebug.NetWork =
                //     $"{AdsDataMgr.Instance.AdRewardVideoNetwork} | {AdsDataMgr.Instance.AdRewardVideoNetwork} | {AdsDataMgr.Instance.AdRewardVideoNetwork}";
                // rvdebug.PlayAdID = AdsDataMgr.Instance.AdRewardVideoID;
                // EventManager.Instance.SendMessage(rvdebug);
                //重置激励视频广告中间信息
                AdsDataMgr.Instance.AdRewardVideoNetwork = "";
                AdsDataMgr.Instance.AdRewardVideoLastShowTime = 0;
                AdsDataMgr.Instance.AdRewardVideoFireScene = "";
                AdsDataMgr.Instance.AdRewardVideoID = "";

                AdsDataMgr.Instance.AdRewardVideoViewBackCount++;
                AdsDataMgr.Instance.AdRewardVideoViewBackTodayCount++;

                AdsDataMgr.Instance.IsShowRewardVideoCloseBack = false;
                AdsDataMgr.Instance.SaveData();
            }
        }

        // 横幅广告相关
        private static bool CheckCanShowBanner()
        {
            return true;
        }

        public static bool ShowBannerAd()
        {
            /*if (CheckCanShowBanner() == false)
            {
                return false;
            }*/

            // 打开广告
            AdWrapper.Instance.showBannerAd();
            return true;
        }

        public static void HideBannerAd()
        {
            AdWrapper.Instance.hideBannerAd();
        }

        // 插屏广告相关
        private static bool CheckCanWatchInterstitialAd()
        {
            if (UserLayerManager.Instance.IsOrganic())
            {
                return true;
            }
            else if (UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.LowUser)
            {
                return true;
            }
            return false;
        }


        // 插屏广告相关
        private static bool CheckCanWatchInterstitialAdNOCD()
        {
            return true;
        }

        /// <summary>
        /// 检查本关是否播放关间插屏
        /// </summary>
        /// <returns></returns>
        public static bool CanWatchInterstitialAd()
        {
#if UNITY_EDITOR
            return EditorADState;
#endif
            return CheckCanWatchInterstitialAd();
        }


        /// <summary>
        /// 检查本关是否播放关间插屏
        /// </summary>
        /// <returns></returns>
        public static bool CanWatchInterstitialAdNOCD()
        {
            return CheckCanWatchInterstitialAdNOCD() && IsInterstitialAdLoaded();
        }

        public static bool ShowInterstitialAd(string gameState, AdsDataMgr.EInterstitiaFireScene fireScene)
        {
            if (CheckCanWatchInterstitialAd() == false)
            {
                return false;
            }

            // 如果播放条件都已经达成，但是广告没有加载完毕
            if (IsInterstitialAdLoaded() == false)
            {
                AdsDataMgr.Instance.AdInsterstitialMissCount++;
                AdsDataMgr.Instance.AdInsterstitialTodayMissCount++;
                AdsDataMgr.Instance.SaveData();
                return false;
            }

            TryShowInterstitialAd(gameState, fireScene);

            return true;
        }

        public static bool ShowInterstitialAdNoCDForHold(string gameState, AdsDataMgr.EInterstitiaFireScene fireScene)
        {
            bool suc = DoShowInterstitialAdNoCD(gameState, fireScene);

            return suc;
        }

        /// <summary>
        /// 播放 Reward Level 关卡插屏
        /// </summary>
        /// <returns></returns>
        public static bool ShowInterstitialAdNoCDForRewardLv(string gameState,
            AdsDataMgr.EInterstitiaFireScene fireScene)
        {
            bool suc = DoShowInterstitialAdNoCD(gameState, fireScene);

            return suc;
        }

        /// <summary>
        /// 播放无CD插屏
        /// </summary>
        /// <param name="gameState"></param>
        /// <param name="fireScene"></param>
        /// <returns></returns>
        public static bool DoShowInterstitialAdNoCD(string gameState, AdsDataMgr.EInterstitiaFireScene fireScene)
        {
            if (!CheckCanWatchInterstitialAdNOCD())
            {
                return false;
            }

            // 如果播放条件都已经达成，但是广告没有加载完毕
            if (IsInterstitialAdLoaded() == false)
            {
                AdsDataMgr.Instance.AdInsterstitialMissCount++;
                AdsDataMgr.Instance.AdInsterstitialTodayMissCount++;
                AdsDataMgr.Instance.SaveData();
                return false;
            }

            TryShowInterstitialAd(gameState, fireScene);
            return true;
        }

        /// <summary>
        /// 尝试播放插屏广告
        /// </summary>
        /// <param name="gameState"></param>
        /// <param name="fireScene"></param>
        private static void TryShowInterstitialAd(string gameState, AdsDataMgr.EInterstitiaFireScene fireScene)
        {
            // 发送打点数据
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_will_view_i");
            dict.Add("from", fireScene.ToString());
            GameDataMgr.Instance.SetCloseAppByAd(true);

            SendAction(dict);

            GameDataMgr.Instance.AddEnterGameTimes(-1);

            // 记录本地数据
            InterstitialGameState = gameState;
            AdsDataMgr.Instance.IsShowInterstitialCloseBack = true;
            AdsDataMgr.Instance.AdInterstitialWillViewCount++;
            AdsDataMgr.Instance.AdInterstitialWillViewTodayCount++;
            AdsDataMgr.Instance.SetAdFireScene(AdsDataMgr.EAdDebugType.Interstitial, fireScene.ToString());
            AdsDataMgr.Instance.SetAdIntervalTime(AdsDataMgr.EAdDebugType.Interstitial, Utils.GetTimeStamp());
            AdsDataMgr.Instance.SaveData();

            GTAEventDefine.InterstitialWillOpen message = new GTAEventDefine.InterstitialWillOpen();
            EventManager.Instance.SendMessage(message);

            AdjustWrapper.Instance.LogEvent("z5ur2v", null);
            
            //标记是因为尝试播放广告开始游戏
            IsTryPlayAD = true;

            // 打开广告
            AdWrapper.Instance.showInterstitialAd();
        }


        
        /// <summary>
        /// 尝试播放插屏广告
        /// </summary>
        /// <param name="gameState"></param>
        /// <param name="fireScene"></param>
        private static void TryShowInterstitialAd(Action<bool> callback, string gameState)
        {
            // 发送打点数据
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_will_view_i");
            dict.Add("from", gameState);
            GameDataMgr.Instance.SetCloseAppByAd(true);

            SendAction(dict);

            GameDataMgr.Instance.AddEnterGameTimes(-1);

            // 记录本地数据
            InterstitialGameState = gameState;
            AdsDataMgr.Instance.IsShowInterstitialCloseBack = true;
            AdsDataMgr.Instance.AdInterstitialWillViewCount++;
            AdsDataMgr.Instance.AdInterstitialWillViewTodayCount++;
            AdsDataMgr.Instance.SetAdFireScene(AdsDataMgr.EAdDebugType.Interstitial, gameState);
            AdsDataMgr.Instance.SetAdIntervalTime(AdsDataMgr.EAdDebugType.Interstitial, Utils.GetTimeStamp());
            AdsDataMgr.Instance.SaveData();

            GTAEventDefine.InterstitialWillOpen message = new GTAEventDefine.InterstitialWillOpen();
            EventManager.Instance.SendMessage(message);

            IsTryPlayAD = true;

            // 打开广告
            AdWrapper.Instance.showInterstitialAd();
        }

        public static bool IsInterstitialAdLoaded()
        {
// #if UNITY_EDITOR
//             return EditorADState;
// #endif
            return AdWrapper.Instance.isInterstitiaAvailable();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ignoreLevel"></param>
        /// <returns></returns>
        public static bool CheckCanWatchRewardAdNoCD(bool ignoreLevel = false)
        {
            return CheckCanWatchRewardAdLoadNew();
        }

        // 激励广告相关
        public static bool CheckCanWatchRewardAd()
        {
            return CheckCanWatchRewardAdLoadNew();
        }

        /// <summary>
        /// 检查激励视频是否可看，不检查 用户分层广告展示次数上限 限制
        /// </summary>
        /// <returns></returns>
        public static bool CheckRAdWithoutTimesLimit()
        {
            // 如果广告没有加载完毕
            if (IsRewardedVideoAdLoaded() == false)
            {
                return false;
            }

            return true;
        }

        public static bool ShowRewardedVideoAd(Action<bool> callback, string from)
        {
            // 注意：激励视频不受去广告影响
            // 注意：卡牌线索的激励视频不受任何条件限制
            if (from == ERVType.DailyReward.ToString())
            {
                if (!CheckCanWatchRewardAdLoadNew())
                {
                    FailedPlayRV();
                    MainManager.Instance.ShowAdError();
                    return false;
                }
            }
            else
            {
                if (!CheckCanWatchRewardAdLoadNew())
                {
                    FailedPlayRV();
                    MainManager.Instance.ShowAdError();
                    return false;
                }
            }
            TryRewardedVideoAdNew(callback, from);
            return true;
        }


        public static bool ShowRewardedVideoAdNoCD(Action<bool> callback, string from)
        {
            if (!CheckCanWatchRewardAdLoadNew())
            {
                FailedPlayRV();
                return false;
            }

            TryRewardedVideoAdNew(callback, from);

            return true;
        }

        private static bool CheckCanWatchRewardAdLoadNew()
        {
            return IsRewardedVideoAdLoaded();
            // return IsRewardedVideoAdLoaded() || IsInterstitialAdLoaded();
        }

        /// <summary>
        /// 尝试
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="from"></param>
        private static void TryRewardedVideoAdNew(Action<bool> callback, string from)
        {
            if (IsRewardedVideoAdLoaded())
            {
                TryRewardedVideoAd(callback, from);
            }
            // else if (IsInterstitialAdLoaded())
            // {
            //     TryShowInterstitialAd(callback, from);
            // }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="adSite"></param>
        /// <param name="callback"></param>
        /// <param name="from"></param>
        private static void TryRewardedVideoAd(Action<bool> callback, string from)
        {
            // 发送打点数据
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_will_view_rv");
            dict.Add("from", from);
            GameDataMgr.Instance.SetCloseAppByAd(true);
            dict.Add("rvload", IsRewardedVideoAdLoaded() ? 1 : 0);
            SendAction(dict);

            GTA.GameDataMgr.Instance.AddEnterGameTimes(-1);

            // 记录本地数据
            AdsDataMgr.Instance.IsShowRewardVideoCloseBack = true;
            AdsDataMgr.Instance.AdRewardVideoWillViewCount++;
            AdsDataMgr.Instance.AdRewardVideoWillViewTodayCount++;
            AdsDataMgr.Instance.SetAdFireScene(AdsDataMgr.EAdDebugType.RewardVideo, from);
            AdsDataMgr.Instance.SetAdIntervalTime(AdsDataMgr.EAdDebugType.RewardVideo, Utils.GetTimeStamp());
            AdsDataMgr.Instance.SaveData();

            //给实体兑换价广告次数
            UIShopManager.Instance.AddRewardAdConut();
            
            AdjustWrapper.Instance.LogEvent("dnq5xj", null);
            
            // 打开广告
            _rewardVideoFrom = from;

            IsTryPlayAD = true;

            AdWrapper.Instance.showRewardedAd(callback);

            _rewardVideCompleted = false;
        }

        public static bool IsRewardedVideoAdLoaded()
        {
// #if UNITY_EDITOR
//             return EditorADState;
// #endif
            return AdWrapper.Instance.isRewardedVideoAvailable();
        }

        /// <summary>
        /// 发送打点数据
        /// </summary>
        public static void SendAction(Dictionary<string, object> dict)
        {
            ActionHelper.SendAction((string)dict["name"], dict);
        }

        // 横幅广告回调
        public void onBannerLoaded()
        {
            AdsDataMgr.Instance.AdBannerLoadedCount++;
            AdsDataMgr.Instance.SaveData();
        }

        public void onBannerLoadFailed()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_failed_b");
            long time = Utils.GetTimeStamp();
            if (AdsDataMgr.Instance.AdBannerFailedTime == 0)
            {
                AdsDataMgr.Instance.AdBannerFailedTime = time;
            }

            dict.Add("FailedInterval", (time - AdsDataMgr.Instance.AdBannerFailedTime));
            AdsDataMgr.Instance.AdBannerFailedTime = time;
            AdsDataMgr.Instance.SaveData();
            SendAction(dict);

            AdsDataMgr.Instance.AdBannerFailedCount++;
            AdsDataMgr.Instance.AdBannerFailedTodayCount++;
            AdsDataMgr.Instance.SaveData();
        }

        public void onBannerClicked()
        {
            IsTryPlayAD = true;
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_click_b");
            SendAction(dict);

            AdsDataMgr.Instance.AdBannerClickCount++;
            AdsDataMgr.Instance.AdBannerClickTodayCount++;
            AdsDataMgr.Instance.SaveData();
        }

        public void onBannerOpened()
        {
            GameLogger.Log("@@@ onBannerOpened.");
            GameDataMgr.Instance.SetCloseAppByAd(true);
        }

        public void onBannerClosed()
        {
        }

        public void onBannerPaid()
        {
            // 发送打点数据
            var dict3 = new Dictionary<string, object> { { "name", "ad_view_b" } };
            ADSHelper.SendAction(dict3);

            // 记录本地数据
            AdsDataMgr.Instance.AdBannerViewCount++;
            AdsDataMgr.Instance.AdBannerViewTodayCount++;
            AdsDataMgr.Instance.SaveData();
        }

        // 插屏广告回调
        public void onInterstitialLoaded()
        {
            GTAEventDefine.InterstitialLoaded message = new GTAEventDefine.InterstitialLoaded();
            EventManager.Instance.SendMessage(message);
        }

        public void onInterstitialLoadFailed()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_failed_i");
            long time = Utils.GetTimeStamp();
            if (AdsDataMgr.Instance.AdInterstitialFailedTime == 0)
            {
                AdsDataMgr.Instance.AdInterstitialFailedTime = time;
            }

            dict.Add("FailedInterval", (time - AdsDataMgr.Instance.AdInterstitialFailedTime));
            AdsDataMgr.Instance.AdInterstitialFailedTime = time;
            AdsDataMgr.Instance.SaveData();
            SendAction(dict);

            AdsDataMgr.Instance.AdInterstitialFailedTodayCount++;
            AdsDataMgr.Instance.AdInterstitialFailedCount++;
            AdsDataMgr.Instance.SaveData();
        }

        /*public void onInterstitialOpened()
        {
            GameDataMgr.Instance.SetCloseAppByAd(true);
            AdsDataMgr.Instance.closeReason = 1;
            AdsDataMgr.Instance.SaveData();

            var dict = new Dictionary<string, object>
            {
                { "name", "ad_view_i" },
                { "from", AdsDataMgr.Instance.GetAdFireScene(AdsDataMgr.EAdDebugType.Interstitial) },
                { "adUnitId", "" }
            };
            SendAction(dict);

            AdsDataMgr.Instance.AdInterstitialPlayTime = Utils.GetTimeStamp();
            AdsDataMgr.Instance.AdInterstitialViewCount++;
            AdsDataMgr.Instance.AdInterstitialViewTodayCount++;
            AdsDataMgr.Instance.SaveData();

            _lastShowInterstitialLevel = DataMainGame.latestLevelID + SaveDataHelper.Instance.GetDailyPassCnt() +
                                         DataManager.Instance.GetData<DataAdventure>().GetCurProgress();
            _lastShowInterstitialTime = Utils.GetTimeStamp();
        }*/

        public void onInterstitialOpened(string adUnitId)
        {
            GameDataMgr.Instance.SetCloseAppByAd(true);
            AdsDataMgr.Instance.closeReason = 1;
            AdsDataMgr.Instance.SaveData();

            var dict = new Dictionary<string, object>
            {
                { "name", "ad_view_i" },
                { "from", AdsDataMgr.Instance.GetAdFireScene(AdsDataMgr.EAdDebugType.Interstitial) },
                { "adUnitId", adUnitId ?? "unknown" }
            };
            SendAction(dict);

            AdsDataMgr.Instance.AdInterstitialPlayTime = Utils.GetTimeStamp();
            AdsDataMgr.Instance.AdInterstitialViewCount++;
            AdsDataMgr.Instance.AdInterstitialViewTodayCount++;
            AdsDataMgr.Instance.SaveData();
            
            _lastShowInterstitialTime = Utils.GetTimeStamp();
            
            //三个活跃日看插屏广告
            MainManager.Instance.CheckThreeDayWatchInterCM();
        }

        public void OnSaveInterstitialTime()
        {
            AdsDataMgr.Instance.AdInterstitialPlayTime = Utils.GetTimeStamp();
            AdsDataMgr.Instance.SaveData();

            _lastShowInterstitialTime = Utils.GetTimeStamp();
        }
        
        public void onInterstitialClicked()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_click_i");
            dict.Add("from", AdsDataMgr.Instance.GetAdFireScene(AdsDataMgr.EAdDebugType.Interstitial));
            SendAction(dict);

            AdsDataMgr.Instance.AdInterstitialClickCount++;
            AdsDataMgr.Instance.AdInterstitialClickTodayCount++;
            AdsDataMgr.Instance.SaveData();
        }

        public void onInterstitialClosed()
        {
            AdsDataMgr.Instance.closeReason = 0;
            AdsDataMgr.Instance.SaveData();

            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_close_i");
            dict.Add("from", AdsDataMgr.Instance.GetAdFireScene(AdsDataMgr.EAdDebugType.Interstitial));
            long watchTime = Utils.GetTimeStamp() - AdsDataMgr.Instance.AdInterstitialPlayTime;
            dict.Add("watchTime", watchTime / 1000);
            SendAction(dict);

            //Dictionary<string, object> dict2 = new Dictionary<string, object>();
            //dict2.Add("name", "ad_viewback_i");
            //dict2.Add("from", "");
            //SendAction(dict2);

            AdsDataMgr.Instance.IsShowInterstitialCloseBack = false;
            AdsDataMgr.Instance.AdInterstitialCloseCount++;
            AdsDataMgr.Instance.AdInterstitialCloseTodayCount++;
            AdsDataMgr.Instance.SaveData();

            GTAEventDefine.InterstitialClosed message = new GTAEventDefine.InterstitialClosed();
            EventManager.Instance.SendMessage(message);
        }

        public void onInterstitiaPaid()
        {
        }

        // 激励广告回调
        public void onRewardedVideoAdLoaded()
        {
            GTAEventDefine.RewardedVideoAdLoaded message = new GTAEventDefine.RewardedVideoAdLoaded();
            EventManager.Instance.SendMessage(message);
        }

        public void onRewardedVideoAdLoadFailed(string error)
        {
            //AdsDataMgr.Instance.AdRewardVideoFailedCount++;
            //AdsDataMgr.Instance.AdRewardVideoFailedTodayCount++;
            //AdsDataMgr.Instance.SaveData();

            //Dictionary<string, object> dict = new Dictionary<string, object>();
            //dict.Add("name", "ad_failed_rv");
            //SendAction(dict);

            //if (ADSHelper.rewardedListener != null)
            //{
            //	ADSHelper.rewardedListener.onRewardedVideoAdLoadFailed(error);
            //}
        }

        /// <summary>
        /// 
        /// </summary>
        public static void FailedPlayRV()
        {
            AdsDataMgr.Instance.AdRewardVideoFailedCount++;
            AdsDataMgr.Instance.AdRewardVideoFailedTodayCount++;
            AdsDataMgr.Instance.SaveData();

            Dictionary<string, object> dicttion = new Dictionary<string, object>();
            dicttion.Add("name", "ad_failed_rv");
            long time = Utils.GetTimeStamp();
            if (AdsDataMgr.Instance.AdRewardVideoFailedTime == 0)
            {
                AdsDataMgr.Instance.AdRewardVideoFailedTime = time;
            }

            dicttion.Add("FailedInterval", (time - AdsDataMgr.Instance.AdRewardVideoFailedTime));
            AdsDataMgr.Instance.AdRewardVideoFailedTime = time;
            AdsDataMgr.Instance.SaveData();
            SendAction(dicttion);
        }

        public void onRewardedVideoAdOpened()
        {
            GameDataMgr.Instance.SetCloseAppByAd(true);
            AdsDataMgr.Instance.closeReason = 1;
            AdsDataMgr.Instance.SaveData();

            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_view_rv");
            dict.Add("from", _rewardVideoFrom);
            SendAction(dict);

            AdsDataMgr.Instance.AdRewardVideoPlayTime = Utils.GetTimeStamp();
            AdsDataMgr.Instance.IsShowRewardVideoCloseBack = true;
            AdsDataMgr.Instance.AdRewardVideoViewCount++;
            AdsDataMgr.Instance.AdRewardVideoViewTodayCount++;
            AdsDataMgr.Instance.SaveData();

            GTAEventDefine.RewardedVideoAdOpen message = new GTAEventDefine.RewardedVideoAdOpen();
            EventManager.Instance.SendMessage(message);
        }

        public void onRewardedVideoAdOpened(string adUnitId)
        {
            GameDataMgr.Instance.SetCloseAppByAd(true);
            AdsDataMgr.Instance.closeReason = 1;
            AdsDataMgr.Instance.SaveData();

            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_view_rv");
            dict.Add("adUnitId", adUnitId);
            dict.Add("from", _rewardVideoFrom);
            SendAction(dict);

            AdsDataMgr.Instance.AdRewardVideoPlayTime = Utils.GetTimeStamp();
            AdsDataMgr.Instance.IsShowRewardVideoCloseBack = true;
            AdsDataMgr.Instance.AdRewardVideoViewCount++;
            AdsDataMgr.Instance.AdRewardVideoViewTodayCount++;
            AdsDataMgr.Instance.SaveData();

            GTAEventDefine.RewardedVideoAdOpen message = new GTAEventDefine.RewardedVideoAdOpen();
            EventManager.Instance.SendMessage(message);
            CheckViewRewardCM();
            //首日播放打点
            MainManager.Instance.CheckFisrtDayWatchRewardCM();
            //
            MainManager.Instance.m_RewardCMTime = 0;
            //OnSaveInterstitialTime();
        }

        private void CheckViewRewardCM()
        {
            int _openGameCount = PlayerPrefs.GetInt("aj_view_rv_3day", 0);
            string _openGamesTime = PlayerPrefs.GetString("aj_view_rv_3day_time", "-1");
            if (_openGamesTime.Equals("-1"))
            {
                PlayerPrefs.SetString("aj_view_rv_3day_time", GTA.Utils.GetTimeStamp().ToString());
                PlayerPrefs.SetInt("aj_view_rv_3day", 1);
            }
            else if (_openGamesTime.Equals("-2"))
            {
                //已经发过事件就不再发了
            }
            else
            {
                long timestamp1 = long.Parse(_openGamesTime); // 第一个时间戳
                long timestamp2 = GTA.Utils.GetTimeStamp(); // 第二个时间戳
                
                DateTimeOffset dateTime1 = DateTimeOffset.FromUnixTimeMilliseconds(timestamp1);
                DateTimeOffset dateTime2 = DateTimeOffset.FromUnixTimeMilliseconds(timestamp2);

                // 计算日期差
                TimeSpan timeSpan = dateTime2.Date - dateTime1.Date;
                int days = Math.Abs(timeSpan.Days);
                if (days > 1)
                {
                    PlayerPrefs.SetString("aj_view_rv_3day_time", GTA.Utils.GetTimeStamp().ToString());
                    PlayerPrefs.SetInt("aj_view_rv_3day", 1);
                }
                else if (days == 1)
                {
                    if (_openGameCount < 2)
                    {
                        PlayerPrefs.SetString("aj_view_rv_3day_time", GTA.Utils.GetTimeStamp().ToString());
                        _openGameCount++;
                        PlayerPrefs.SetInt("aj_view_rv_3day", _openGameCount);
                
                    }
                    else
                    {
                        AnalyticsHelper.LogEvent("APPSFLYER", "st10dy", null);
                        //发送连续三天的事件
                        PlayerPrefs.SetString("aj_view_rv_3day_time", "-2");
                        PlayerPrefs.SetInt("aj_view_rv_3day", -9999);
                    }
                }
            }
        }
        
        public void onRewardedVideoAdClosed()
        {
            AdsDataMgr.Instance.closeReason = 0;
            AdsDataMgr.Instance.SaveData();

            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_close_rv");
            dict.Add("from", _rewardVideoFrom);
            dict.Add("finish", _rewardVideCompleted ? "1" : "0");
            long watchTime = Utils.GetTimeStamp() - AdsDataMgr.Instance.AdRewardVideoPlayTime;
            dict.Add("watchTime", watchTime / 1000);
            SendAction(dict);

            _rewardVideCompleted = false;

            AdsDataMgr.Instance.IsShowRewardVideoCloseBack = false;
            AdsDataMgr.Instance.AdRewardVideoCloseCount++;
            AdsDataMgr.Instance.AdRewardVideoCloseTodayCount++;
            AdsDataMgr.Instance.SaveData();

            GTAEventDefine.RewardedVideoAdClosed message = new GTAEventDefine.RewardedVideoAdClosed();
            EventManager.Instance.SendMessage(message);
        }

        public void onRewardedVideoAdClicked()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("name", "ad_click_rv");
            dict.Add("from", _rewardVideoFrom);
            SendAction(dict);

            AdsDataMgr.Instance.AdRewardVideoClickCount++;
            AdsDataMgr.Instance.AdRewardVideoClickTodayCount++;
            AdsDataMgr.Instance.SaveData();
        }

        public void onRewardedVideoAdShowFailed(string error)
        {
            Dictionary<string, object> dict2 = new Dictionary<string, object>();
            dict2.Add("name", "ad_playfailed_rv");
            SendAction(dict2);

            AdsDataMgr.Instance.IsShowRewardVideoCloseBack = false;
            AdsDataMgr.Instance.AdRewardVideoPlayFailedCount++;
            AdsDataMgr.Instance.AdRewardVideoPlayFailedTodayCount++;
            AdsDataMgr.Instance.SaveData();
        }

        public void onRewardedVideoAdCompleted()
        {
            // 注意：卡牌线索的激励视频不计入次数
            // 视频观看完毕，才计算一次次数
            if (_rewardVideoFrom != ERVType.RandomTipDiffSave.ToString())
            {
                AdsDataMgr.Instance.AdRewardVideoLimitTodayCount++;

                ADEvent.RecieveRVReward rrv = new ADEvent.RecieveRVReward();
                EventManager.Instance.SendMessage(rrv);
            }

            AdsDataMgr.Instance.closeReason = 0;
            AdsDataMgr.Instance.SaveData();

            _rewardVideCompleted = true;

            GTAEventDefine.RewardedVideoCompleted message = new GTAEventDefine.RewardedVideoCompleted();
            EventManager.Instance.SendMessage(message);
            HasPlayRV = true;
        }

        public void onRewardedVideoPaid()
        {
        }

        private void HandleEvent(IEventMessage msg)
        {
            if (msg is ADEvent.GetNoAd)
            {
                //HideBannerAd();
            }
        }
    }
}